// 引入宠物服务
const petService = require('../../services/pet');

Page({
  data: {
    petId: null,
    petTypes: ['猫', '狗', '兔子', '鸟类', '其他'],
    typeIndex: 0,
    pet: {
      name: '',
      type: '猫',
      breed: '',
      gender: 0,
      photo: '',
      weight: '',
      birthDate: '',
      is_sterilized: 0,
      remarks: ''
    },
    genders: ['未知', '公', '母'],
    genderIndex: 0,
    today: '',
    isLoading: true
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if (options.id) {
      const petId = parseInt(options.id);
      this.setData({ petId });
      this.loadPetDetail(petId);
    } else {
      wx.showToast({
        title: '参数错误',
        icon: 'none'
      });
      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
    }
    
    // 设置今天日期为选择器结束日期
    const today = new Date();
    const year = today.getFullYear();
    const month = today.getMonth() + 1;
    const day = today.getDate();
    
    this.setData({
      today: `${year}-${month < 10 ? '0' + month : month}-${day < 10 ? '0' + day : day}`
    });
  },

  /**
   * 加载宠物详情
   */
  loadPetDetail(id) {
    wx.showLoading({
      title: '加载中...',
    });

    petService.getPetDetail(id)
      .then(petData => {
        // 兼容字段名差异
        let typeIndex = 0;
        if (this.data.petTypes.indexOf(petData.type) !== -1) {
          typeIndex = this.data.petTypes.indexOf(petData.type);
        }
        
        // 兼容各种字段名
        if (petData.birthday && !petData.birthDate) {
          petData.birthDate = petData.birthday;
        }
        if (petData.birth_date && !petData.birthDate) {
          petData.birthDate = petData.birth_date;
        }
        
        if (petData.isStatilized !== undefined && petData.is_sterilized === undefined) {
          petData.is_sterilized = petData.isStatilized ? 1 : 0;
        }
        
        this.setData({
          pet: petData,
          genderIndex: petData.gender || 0,
          typeIndex: typeIndex,
          isLoading: false
        });
        wx.hideLoading();
      })
      .catch(err => {
        console.error('获取宠物详情失败', err);
        wx.hideLoading();
        wx.showToast({
          title: '获取宠物详情失败',
          icon: 'none'
        });
        setTimeout(() => {
          wx.navigateBack();
        }, 1500);
      });
  },

  /**
   * 表单输入处理
   */
  onInput(e) {
    const { field } = e.currentTarget.dataset;
    const { value } = e.detail;
    
    this.setData({
      [`pet.${field}`]: value
    });
  },

  /**
   * 宠物类型选择器变化
   */
  bindTypeChange(e) {
    const typeIndex = parseInt(e.detail.value);
    this.setData({
      typeIndex,
      'pet.type': this.data.petTypes[typeIndex]
    });
  },

  /**
   * 性别选择器变化
   */
  bindGenderChange(e) {
    const genderIndex = parseInt(e.detail.value);
    this.setData({
      genderIndex,
      'pet.gender': genderIndex
    });
  },

  /**
   * 出生日期选择器变化
   */
  bindDateChange(e) {
    this.setData({
      'pet.birthDate': e.detail.value
    });
  },
  
  /**
   * 绝育状态变化
   */
  bindSterilizedChange(e) {
    this.setData({
      'pet.is_sterilized': e.detail.value ? 1 : 0
    });
  },

  /**
   * 上传宠物照片
   */
  uploadPhoto() {
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        const tempFilePath = res.tempFilePaths[0];
        
        wx.showLoading({
          title: '上传中...',
        });
        
        wx.uploadFile({
          url: `${getApp().globalData.baseUrl}/pet/photo`,
          filePath: tempFilePath,
          name: 'file',
          header: {
            'Authorization': wx.getStorageSync('token')
          },
          success: (res) => {
            const data = JSON.parse(res.data);
            if (data.code === 200) {
              this.setData({
                'pet.photo': data.data
              });
              wx.showToast({
                title: '上传成功',
                icon: 'success'
              });
            } else {
              wx.showToast({
                title: data.message || '上传失败',
                icon: 'none'
              });
            }
          },
          fail: () => {
            wx.showToast({
              title: '上传失败',
              icon: 'none'
            });
          },
          complete: () => {
            wx.hideLoading();
          }
        });
      }
    });
  },

  /**
   * 提交表单
   */
  submitForm() {
    const { pet, petId } = this.data;
    
    if (!pet.name) {
      wx.showToast({
        title: '请输入宠物名称',
        icon: 'none'
      });
      return;
    }
    
    if (!pet.type) {
      wx.showToast({
        title: '请选择宠物类型',
        icon: 'none'
      });
      return;
    }
    
    wx.showLoading({
      title: '保存中...',
    });
    
    // 设置ID用于更新
    pet.id = petId;
    
    // 确保字段名匹配数据库
    const petData = {
      ...pet,
      birthday: pet.birthDate,
      birthDate: pet.birthDate,
      birth_date: pet.birthDate,
      isStatilized: pet.is_sterilized === 1
    };
    
    petService.updatePet(petData)
      .then(() => {
        wx.hideLoading();
        wx.showToast({
          title: '保存成功',
          icon: 'success'
        });
        
        // 返回上一页
        setTimeout(() => {
          wx.navigateBack();
        }, 1500);
      })
      .catch(err => {
        console.error('更新宠物信息失败', err);
        wx.hideLoading();
        wx.showToast({
          title: err.message || '保存失败',
          icon: 'none'
        });
      });
  },
  
  /**
   * 删除宠物
   */
  deletePet() {
    wx.showModal({
      title: '确认删除',
      content: '确定要删除该宠物信息吗？删除后无法恢复。',
      confirmColor: '#e64340',
      success: (res) => {
        if (res.confirm) {
          wx.showLoading({
            title: '删除中...',
          });
          
          petService.deletePet(this.data.petId)
            .then(() => {
              wx.hideLoading();
              wx.showToast({
                title: '删除成功',
                icon: 'success'
              });
              
              setTimeout(() => {
                wx.navigateBack({
                  delta: 1
                });
              }, 1500);
            })
            .catch(err => {
              wx.hideLoading();
              wx.showToast({
                title: err.message || '删除失败',
                icon: 'none'
              });
            });
        }
      }
    });
  }
}) 